/**
 * 当前Tab截图服务
 */
import moment from "moment"

import type { PlasmoMessaging } from "@plasmohq/messaging"

import { dataURItoBlob } from "~/utils/tools"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
  const { body, sender } = req
  const { tab } = sender
  // 是否需要保存图片
  const toSave = body.toSave || false
  // 保存图片的文件名称
  const fileName = body.fileName || "截图"
  // 截图操作
  const image = await chrome.tabs.captureVisibleTab(tab?.windowId || null, {
    format: "png"
  })
  // 保存图片操作
  if (toSave) {
    // 保存图片
    const blob = dataURItoBlob(image)
    const reader = new FileReader()
    reader.onload = () => {
      const buffer = reader.result
      const blobUrl = `data:${blob.type};base64,${btoa(
        new Uint8Array(buffer as ArrayBuffer).reduce(
          (data, byte) => data + String.fromCharCode(byte),
          ""
        )
      )}`
      chrome.downloads.download(
        {
          url: blobUrl,
          filename: `${fileName}.png`
        },
        () => {
          res.send({ image: image })
        }
      )
    }
    reader.readAsArrayBuffer(blob)
  } else {
    res.send({ image: image })
  }
}

export default handler
